package collectionDemo.propertyDir;

import org.apache.log4j.Logger;
import org.junit.Test;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author Ajie
 * @date 2020-10-16
 * @function
 * todo
 */
public class PropertyDemo {
    private static final Logger logger =  Logger.getLogger(PropertyDemo.class);
    private String proFilePath = "./src/collectionDemo/propertyDir/setting.properties";

    @Test
    public void getPro() throws UnsupportedEncodingException {
        String settings = "# test" + "\n" + "course=Java" + "\n" + "last_open_date=2019-08-07T12:35:01";
        ByteArrayInputStream input = new ByteArrayInputStream(settings.getBytes("UTF-8"));
        Properties props = new Properties();
        try {
            props.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("course: " + props.getProperty("course"));
        System.out.println("last_open_date: " + props.getProperty("last_open_date"));
        System.out.println("last_open_file: " + props.getProperty("last_open_file"));
        System.out.println("auto_save: " + props.getProperty("auto_save", "60"));
    }

    @Test
    public void getProLoadFile() throws UnsupportedEncodingException {
        Properties props = new Properties();
        try {
            props.load(new FileReader(proFilePath));
            //待验证---
            // 早期版本的Java规定.properties文件编码是ASCII编码（ISO8859-1），如果涉及到中文就必须用name=\u4e2d\u6587来表示，非常别扭。
            // 从JDK9开始，Java的.properties文件可以使用UTF-8编码了。
//            props.load(new FileReader(proFilePath, StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Iterator<Map.Entry<Object, Object>> iterator = props.entrySet().iterator();

        while (iterator.hasNext()){
            Map.Entry<Object, Object> next = iterator.next();
            Object key = next.getKey();
            Object value = next.getValue();
            logger.info("getProLoadFile: key:"+key+"  v:"+value);
        }
    }

    @Test
    public void setPro(){
        Properties props = new Properties();
        props.setProperty("url", "http://www.liaoxuefeng.com");
        props.setProperty("language", "Java");
        try {
            props.store(new FileOutputStream(proFilePath), "this is properties discribe");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void setPro2(){
        Properties props = new Properties();
        props.setProperty("url", "http://www.liaoxuefeng.com222");
        try {
            props.store(new FileOutputStream(proFilePath), "this is properties discribe 222");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
